<?php
declare (strict_types = 1);

namespace app\user\model;

use think\facade\Db;
use think\Model;

/**
 * @mixin \think\Model
 */
class MiaoLog extends Model
{
    public $page = '';//分页数据
    public $count = '';//数据总数
    public $error = '';//报错

    /*
     * 获取用户喵呗记录
     */
    public function getMiaoList($id){
        try{
            if(empty($id)) exception('找不到该用户!');
            $data = Input('post.');
            $type = isset($data['type'])&&!empty($data['type']) ? $data['type'] : 1;
            $where = ['uid' => $id,'status'=>3,'is_delete'=>0];
            $field = "CONCAT( CASE WHEN type = 1 THEN '视频收益' WHEN type = 2 THEN '拼团活动' WHEN type = 3 THEN '团队奖励' ELSE '分享奖励' END,
            CASE WHEN type = 4 THEN '(购物)' WHEN type = 5 THEN '(购物)' WHEN type = 6 THEN '(视频)' WHEN type = 7 THEN '(直播)' ELSE '' END ) as type
            ,uid,reward as balance,add_time";
            if($type == 1) {
                $limit = isset($data['limit'])&&!empty($data['limit']) ? $data['limit'] : 15;//每页显示数据
                $query = ['page' => (isset($data['page']) ? $data['page'] : 1)];//分页参数
                $item = $this->field($field)->where($where)->order('add_time desc')->paginate($limit, false, array('query'=>$query));
                $list = empty($item) ? array():$item->toArray();
                if (!empty($list['data'])) {
                    foreach ($list['data'] as $k => $v) {
                        $list['data'][$k]['balance'] = getformat($v['balance']);
                        $list['data'][$k]['add_time'] = date('Y-m-d H:i', $v['add_time']);
                    }
                }
            }else{
                $mod = new UserCash();
                $list = $mod->exchangeList($id,$isReturn =1);
                if($list == false&&!empty($mod->error))
                    exception($mod->error);
            }

            $data = [
                'miao'=> (new UserWallet())->getWallet($id)['miao'],
                'list'=>$list
            ];
            return $data;
        }catch (\Exception $e){
            if(stristr($e->getMessage(),'SQLSTATE')){
                $this->error = '数据走丢了，请稍后再试！';
            }else $this->error = $e->getMessage();
            return false;
        }
    }

    /*
     * 用户喵呗收益
     */
    public function miaoReward($id){
        try{
            if(empty($id)) exception('找不到该用户!');
            $data = Input('post.');
            $where[] = ['uid','=',$id];
            $where[] = ['is_delete','=',0];
            if(!empty($data['type'])){
                if($data['type'] == 4) $where[] = ['type','between','4,7'];
                else $where[] = ['type','=',$data['type']];
            }
            $field = "sum(IF(status=3,reward,0)) as total,sum(IF(status=1,reward,0)) as estimate,sum(IF(status=2,reward,0)) as settlement,sum(IF(status=4,reward,0)) as invalid";
            $list = $this->field($field)->where($where)->find();
            if (!empty($list)) {
                $list['total'] = getformat($list['total']);
                $list['estimate'] = getformat($list['estimate']);
                $list['settlement'] = getformat($list['settlement']);
                $list['invalid'] = getformat($list['invalid']);
            }
            return $list;
        }catch (\Exception $e){
            if(stristr($e->getMessage(),'SQLSTATE')){
                $this->error = '数据走丢了，请稍后再试！';
            }else $this->error = $e->getMessage();
            return false;
        }
    }

    /*
     * 用户团队收益
     */
    public function teamReward($id){
        try{
            if(empty($id)) exception('找不到该用户!');
            //FROM_UNIXTIME(add_time, '%c') 月  FROM_UNIXTIME(add_time, '%u') 周
            $day = date('Y-m-d',time());
            $yesterday =  date('Y-m-d',strtotime($day." -1 day"));
            $week = date('W',time());//周
            $month = (int)date('m',time());//月
            $where[] = ['uid','=',$id];
            $where[] = ['status','=',3];
            $where[] = ['type','=',3];
            $where[] = ['is_delete','=',0];
            $field = "sum(IF(FROM_UNIXTIME(add_time, '%Y-%m-%d')='{$day}',reward,0)) as day,sum(IF(FROM_UNIXTIME(add_time, '%Y-%m-%d')='{$yesterday}',reward,0)) as yesterday,
            sum(IF(FROM_UNIXTIME(add_time, '%u')='{$week}',reward,0)) as week,sum(IF(FROM_UNIXTIME(add_time, '%c')='{$month}',reward,0)) as month,sum(reward) as total";
            $list = $this->field($field)->where($where)->find();
            if (!empty($list)) {
                $yearMap = ['day','yesterday','week','month','total'];
                foreach($yearMap as $v){
                    $list[$v] = getformat($list[$v]);
                }
            }
            $list['invite_num'] = (new UserInvite())->getInviteNum($id);
            return $list;
        }catch (\Exception $e){
            if(stristr($e->getMessage(),'SQLSTATE')){
                $this->error = '数据走丢了，请稍后再试！';
            }else $this->error = $e->getMessage();
            return false;
        }
    }

    /*
     * 用户视频收益
     */
    public function videoReward($id){
        try{
            if(empty($id)) exception('找不到该用户!');
            $where[] = ['uid','=',$id];
            $where[] = ['status','=',3];
            $where[] = ['type','=',1];
            $where[] = ['is_delete','=',0];
            $field = "IFNULL(sum(reward),0.00) as miao_total";
            $list = $this->field($field)->where($where)->find();
            $data = (new UserVideoProfit())->getUserVideoLog($id);
            $data['miao_total'] = empty($list) ? '0.00' : getformat($list['miao_total']);
            return $data;
        }catch (\Exception $e){
            if(stristr($e->getMessage(),'SQLSTATE')){
                $this->error = '数据走丢了，请稍后再试！';
            }else $this->error = $e->getMessage();
            return false;
        }
    }

    /*
     * 用户历史结算 按一年12个月
     */
    public function historyList($id){
        try{
            if(empty($id)) exception('找不到该用户!');
            $data = Input('post.');
            $date = isset($data['date']) ? $data['date'] : date('Y',time());
            $where[] = ['uid','=',$id];
            $where[] = ['status','=',3];
            $where[] = ['is_delete','=',0];
            if(!empty($data['type'])){
                if($data['type'] == 4) $where[] = ['type','between','4,7'];
                else $where[] = ['type','=',$data['type']];
            }
            $field = "sum(IF(FROM_UNIXTIME(add_time, '%Y-%m')='{$date}-01',reward,0)) as one,sum(IF(FROM_UNIXTIME(add_time, '%Y-%m')='{$date}-02',reward,0)) as two,sum(IF(FROM_UNIXTIME(add_time, '%Y-%m')='{$date}-03',reward,0)) as three,
            sum(IF(FROM_UNIXTIME(add_time, '%Y-%m')='{$date}-04',reward,0)) as four,sum(IF(FROM_UNIXTIME(add_time, '%Y-%m')='{$date}-05',reward,0)) as five,sum(IF(FROM_UNIXTIME(add_time, '%Y-%m')='{$date}-06',reward,0)) as six,
            sum(IF(FROM_UNIXTIME(add_time, '%Y-%m')='{$date}-07',reward,0)) as seven,sum(IF(FROM_UNIXTIME(add_time, '%Y-%m')='{$date}-08',reward,0)) as eight,sum(IF(FROM_UNIXTIME(add_time, '%Y-%m')='{$date}-09',reward,0)) as nine,
            sum(IF(FROM_UNIXTIME(add_time, '%Y-%m')='{$date}-10',reward,0)) as ten,sum(IF(FROM_UNIXTIME(add_time, '%Y-%m')='{$date}-11',reward,0)) as eleven,sum(IF(FROM_UNIXTIME(add_time, '%Y-%m')='{$date}-12',reward,0)) as twelve";
            $list = $this->field($field)->where($where)->find();
            if (!empty($list)) {
                $yearMap = ['one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve'];
                foreach($yearMap as $v){
                    $list[$v] = getformat($list[$v]);
                }
            }
            return $list;
        }catch (\Exception $e){
            if(stristr($e->getMessage(),'SQLSTATE')){
                $this->error = '数据走丢了，请稍后再试！';
            }else $this->error = $e->getMessage();
            return false;
        }
    }

    /*
     * 团队结算
     * type 1-商品订单 2-购物券
     */
    public function teamSettlement($data,$order){
        try{
            if(empty($data)||!is_array($data)) exception('数据为空!');
            if(empty($order)||!is_array($order)) exception('订单数据为空!');
            if(empty($data['uid'])) exception('用户信息为空!');
            if(empty($data['type'])||!in_array($data['type'],[1,2])) exception('类型错误!');
            $userInviteModel = new UserInvite();
            $walletModel = new UserWallet();
            $userModel = new User();
            #获取上级关系链
            $oid = isset($order['id']) ? $order['id'] : 0;
            $total = $order['pay_amount'];
            $userTeam = $userInviteModel->where(['uid'=>$data['uid']])->find();
            $puserTeam = [];
            if(!empty($userTeam['upid']))
                $puserTeam = $userInviteModel->where(['uid'=>$userTeam['upid']])->find();
            if(empty($puserTeam)){
                $wallet = ['uid'=>$data['uid'],'reward'=>$total,'status'=>1,'type'=>5,'extend'=>'user_volume','extend_id'=>$oid,'add_time'=>time(),'describe'=>'个人累计消费'];
                (new WalletOperationLog())->insert($wallet);
                $walletModel->where('uid',$data['uid'])->inc('consume',$total)->update();
                return true;
            }
            $arr = explode(',',$puserTeam['level']);
            $pids = array_diff($arr,[$puserTeam['upid']]);
            $userIds = array_merge([$data['uid'],$puserTeam['uid'],$puserTeam['upid']],array_reverse($pids));
            #获取等级配置
            $levelInfo = [];
            $level = (new UserLevel())->field('id,coupon_type,coupon_team,coupon_team_twe,coupon_manage,level as level_val')->where(['is_delete'=>0])->select()->toArray();#会员等级信息
            foreach($level as $key=>$val){ $levelInfo[$val['id']] = $val; } //根据用户等级和等级表id 进行建名关联
            #获取用户/钱包数据
            $userWallet = $walletModel->field('uid,volume_balance,volume_total,miao,miaos,pre_miao,wait_miao,consume,teams')->whereIn('uid',$userIds)->select()->toArray();
            $userInfo = $userModel->field('id,level,binding_time')->whereIn('id',$userIds)->select()->toArray();
            $userInvite = [];
            $userM = [];
            #将用户/钱包/等级信息按原排序组装
            foreach($userIds as $kk=>$vv){
                foreach($userInfo as $k=>$v){
                    if($v['id'] == $data['uid']) $userM = empty($userM)? $v : array_merge($userM, $v);
                    if($v['id'] == $vv && $v['id']!=$data['uid']){
                        $userInvite[$kk] = empty($userInvite[$kk])? $v : array_merge($userInvite[$kk], $v);
                    }
                }
                /*foreach($userWallet as $keys=>$value){
                    if($value['uid'] == $data['uid']) $userM = empty($userM)? $value : array_merge($userM, $value);
                    if($value['uid'] == $vv && $value['uid']!=$data['uid']){
                        $userInvite[$kk] = empty($userInvite[$kk])? $value : array_merge($userInvite[$kk], $value);
                    }
                }*/
            }
            #等级佣金比例&直推/间推 提取
            foreach($userInvite as $key=>$val){
                $userInvite[$key]['coupon_type'] = 0;
                $userInvite[$key]['coupon_team'] = 0;
                $userInvite[$key]['coupon_team_twe'] = 0;
                $userInvite[$key]['coupon_manage'] = 0;
                $userInvite[$key]['commit_manage'] = 0;
                $userInvite[$key]['commit_team'] = 0;
                $userInvite[$key]['ratio'] = 0;
                if(isset($levelInfo[$val['level']]) && $val['level'] == $levelInfo[$val['level']]['id']){
                    $userInvite[$key]['coupon_type'] = $levelInfo[$val['level']]['coupon_type'];
                    $userInvite[$key]['coupon_team'] = ($levelInfo[$val['level']]['coupon_team']>0) ? $levelInfo[$val['level']]['coupon_team']/1000 : 0;
                    $userInvite[$key]['coupon_team_twe'] = ($levelInfo[$val['level']]['coupon_team_twe']>0) ? $levelInfo[$val['level']]['coupon_team_twe']/1000 : 0;
                    $userInvite[$key]['coupon_manage'] = ($levelInfo[$val['level']]['coupon_manage']>0) ? $levelInfo[$val['level']]['coupon_manage']/1000 : 0;
                }
                if($val['id'] == $puserTeam['uid']){ #直推
                    if($userInvite[$key]['coupon_type'] == 2) $userInvite[$key]['commit_team'] = $userInvite[$key]['coupon_team']*100*1000;
                    else{
                        $userInvite[$key]['ratio'] = $userInvite[$key]['coupon_team'];
                        $userInvite[$key]['commit_team'] = $userInvite[$key]['coupon_team']*$total;
                    }
                }
                if($val['id'] == $puserTeam['upid']){ #间推
                    $userInvite[$key]['ratio'] = $userInvite[$key]['coupon_team_twe'];
                    $userInvite[$key]['commit_team'] = $userInvite[$key]['coupon_team_twe']*$total;
                }
            }
            $pows = 0.8;
            $pows_num = 1;
            $manage_commit = $coupon_manage_commit = 0;
            #管理津贴 提取 按层级进行计算，每级递减百分之20
            foreach($userInvite as $item=>$value){
                if($value['id'] == $data['uid'] || $value['id'] == $puserTeam['uid'] || $value['id'] == $puserTeam['upid']) continue;
                if($manage_commit > 0){
                    if($value['level']>1 && getformat(($value['coupon_manage']*$total*pow($pows,$pows_num))*100) < 1) $coupon_manage_commit = 1;
                    else $coupon_manage_commit = (int)getformat(($value['coupon_manage']*$total*pow($pows,$pows_num))*100);
                    $userInvite[$item]['ratio'] = $value['coupon_manage']*pow($pows,$pows_num);
                    $pows_num++;
                }else{
                    $userInvite[$item]['ratio'] = $value['coupon_manage'];
                    $coupon_manage_commit = $value['coupon_manage']*$total;
                }
                $userInvite[$item]['commit_manage'] = $coupon_manage_commit;
                $manage_commit++;
            }
            $miao = $wallet = [];$i = 1;$time = time();
            $updateInfoSql = 'insert into m3_user_info (uid,consume,team_consume,team_order_num)  values(%s,%s,%s,%s) on  DUPLICATE key update consume=consume+values(consume),team_consume=team_consume+values(team_consume),team_order_num=team_order_num+values(team_order_num)';
            $this::startTrans();
            #写入个人消费记录
            $wallet[0] = ['uid'=>$userM['id'],'reward'=>$total,'status'=>1,'type'=>5,'extend'=>'user_volume','extend_id'=>$oid,'add_time'=>$time,'describe'=>'个人累计消费'];
            $walletModel->where('uid',$userM['id'])->inc('consume',$total)->update();
            if(!empty($userM['binding_time'])&&$userM['binding_time']>0&&$userM['binding_time']<=$time){
                $sql = sprintf($updateInfoSql, $userM['id'], $total, 0, 1);//更新用户绑定后消费数据
                if(!Db::execute($sql))
                    fileLog(date('Y-m-dHis',time()).'-volume回调-团队结算-更新userInfo失败：'.json_encode(['sql'=>$sql,'uid'=>$userM['id'],'total'=>$total]),(date('Y-m-d').'_volume_update_userInfo.log'));
            }
            #组装记录数组批量写入&更新钱包佣金等数据
            foreach($userInvite as $k=>$v){
                $commit = ($v['commit_team']+$v['commit_manage']);
                $wallet[$i] = ['uid'=>$v['id'],'reward'=>$total,'status'=>1,'type'=>5,'extend'=>'user_volume','extend_id'=>$oid,'add_time'=>$time,'describe'=>'团队累计消费'];
                if($commit>0){
                    $i=$i+1;
                    $wallet[$i] = ['uid'=>$v['id'],'reward'=>$commit,'status'=>1,'type'=>2,'extend'=>'user_volume','extend_id'=>$oid,'add_time'=>$time,'describe'=>'购物券团队结算(喵呗)'];
                    $i=$i+1;
                    $miao[$i] = ['uid'=>$v['id'],'oid'=>$oid,'type'=>3,'order_type'=>$data['type'],'reward'=>$commit,'status'=>(($data['type'] == 2) ? 3 : 1),'money'=>$total,'proportion'=>$v['ratio'],'add_time'=>$time,'end_time'=>$time];
                }
                $wl = $walletModel->where('uid',$v['id'])->inc('miao',$commit)->inc('miaos',$commit)->inc('teams',$total)->update();#更新钱包数据miao，miaos，teams
                $sql = sprintf($updateInfoSql, $v['id'], 0, $total, 1);//更新用户绑定后消费数据
                if(!Db::execute($sql))
                    fileLog(date('Y-m-dHis',time()).'-volume回调-团队结算-更新userInfo失败：'.json_encode(['sql'=>$sql,'uid'=>$v['id'],'total'=>$total]),(date('Y-m-d').'_volume_update_userInfo.log'));
                $i++;
            }
            #fileLog(date('Y-m-dHis',time()).'-volume回调-团队结算-更新userInfo：'.json_encode(['miao'=>$miao,'userInvite'=>$userInvite,'wallet'=>$wallet,'level'=>$level]),(date('Y-m-d').'_volume_update_userInfo.log'));
            if(!empty($wallet)){
                if(!empty($wallet)){
                    $wallet = array_values($wallet);
                    (new WalletOperationLog())->insertAll($wallet);
                }
            }
            if(!empty($miao)){
                $miao = array_values($miao);
                if($this->insertAll($miao)){
                    $this::commit();
                    return true;
                }
                fileLog(date('Y-m-dHis',time()).'-volume回调-团队结算-喵呗新增失败：'.json_encode(['userInvite'=>$userInvite,'order'=>$order,'miao'=>$miao,'wallet'=>$wallet]),(date('Y-m-d').'_volume_miao_error.log'));
                //exception('miao_log 新增失败!');
            }else{
                $this::commit();
                fileLog(date('Y-m-dHis',time()).'-volume回调-没有喵呗记录：'.json_encode(['userInvite'=>$userInvite,'order'=>$order,'miao'=>$miao,'wallet'=>$wallet]),(date('Y-m-d').'_volume_miao_error.log'));
                //exception('没有miao_log!');
            }
            return true;
        }catch (\Exception $e){
            $this::rollback();
            fileLog(date('Y-m-dHis',time()).'-volume回调-团队结算异常：'.json_encode(['data'=>$data,'order'=>$order,'err'=>$e->getTrace()[0],'msg'=>$e->getMessage()]),(date('Y-m-d').'_volume_miao_error.log'));
            $this->error = $e->getMessage();
            return false;
        }
    }

    /*
     * 团队结算
     * type 1-商品订单 2-购物券
     */
    public function teamSettlementsss($data,$order){
        try{
            if(empty($data)||!is_array($data)) exception('数据为空!');
            if(empty($order)||!is_array($order)) exception('订单数据为空!');
            if(empty($data['uid'])) exception('用户信息为空!');
            if(empty($data['type'])||!in_array($data['type'],[1,2])) exception('类型错误!');
            #开启团队累计
            $userInviteModel = new UserInvite();
            $userInvite = $userInviteModel->loopTop($data['uid']);
            $userModel = new User();
            if(empty($userInvite)){
                $userInvite = $userModel->where(['id'=>$data['uid'],'is_delete'=>0])->field('id as uid,invite_id as upid,0 as pid,level,binding_time')->select();
                if(!empty($userInvite)) $userInvite = $userInvite->toArray();
                else exception('没有参与结算用户!');
            }
            #按用户关系层级排序
            $last_names = array_column($userInvite,'pid');
            array_multisort($last_names,SORT_DESC,$userInvite);
            $level = (new UserLevel())->field('id,team,manage,level as level_val,direct_push,team_num')->where(['is_delete'=>0])->select()->toArray();#会员等级信息
            $levelInfo = [];
            $model = new UserWallet();
            foreach($level as $key=>$val){ $levelInfo[$val['id']] = $val; } //根据用户等级和等级表id 进行建名关联
            $topUser = $userModel->where(['id'=>$userInvite[count($last_names)-1]['upid']])->field('id as uid,invite_id as upid,0 as pid,level,binding_time')->find();
            if(!empty($topUser)){
                array_push($userInvite,$topUser); #如果存在上级则追加到数组末尾
                if($topUser['upid'] > 0){
                    $topUser = $userModel->where(['id'=>$topUser['upid']])->field('id as uid,invite_id as upid,0 as pid,level,binding_time')->find();
                    if(!empty($topUser)){
                        //foreach($userInvite as $k=>$v){ $userInvite[$k]['pid'] = $v['pid']+1; } //修改pid
                        array_push($userInvite,$topUser); #再次判断上级，如果存在上级则追加到数组末尾
                    }
                }
            }
            #组装用户信息和等级信息
            foreach($userInvite as $kk=>$vv){
                if($vv['level'] == $levelInfo[$vv['level']]['id']){
                    $userInvite[$kk]['team'] = ($levelInfo[$vv['level']]['team']>0) ? $levelInfo[$vv['level']]['team']/100 : 0;
                    $userInvite[$kk]['manage'] = ($levelInfo[$vv['level']]['manage']>0) ? $levelInfo[$vv['level']]['manage']/1000 : 0;
                }
                $userWallet = $model->where(['uid'=>$vv['uid'],'is_delete'=>0])->field('volume_balance,volume_total,miao,miaos,pre_miao,wait_miao,consume,teams')->find();
                $userInvite[$kk] = array_merge(json_decode(json_encode($userInvite[$kk]),true), !empty($userWallet)?json_decode(json_encode($userWallet),true):[]);
            }
            #按等级进行分佣 同等级按管理津贴算，非同等级按团队佣金算
            $oid = $order['id']??0;$total = 0;
            if($data['type'] == 2) $total = $order['pay_amount'];
            else{
                foreach($order as $v){ $total += $v['total'];$oid=$v['order_id']; }
            }
            $levels = 0;#遍历后判断用户等级比$level高则赋值给$level，如果出现等级 1->5->3->5->2则出现第一个5之后不能再分佣只能得到管理津贴
            $is_manage_commit = $manage_commit = 0;
            foreach($userInvite as $item=>$value){
                if($item > 0){
                    #判断用户等级是否比$level高，低则取管理津贴
                    if($value['level'] > $levels){
                        #判断用户是否有团队分佣
                        if(!empty($value['team'])&&$value['team']>0){
                            #判断前面是否有用户取得团队分佣
                            if(!empty($levelInfo[$levels]['team'])&&$levelInfo[$levels]['team']>0){
                                if($value['team'] > ($levelInfo[$levels]['team']/100)) $userInvite[$item]['commit'] = ($total*$value['team'])-($total*($levelInfo[$levels]['team']/100));
                                else $userInvite[$item]['commit'] = 0; #前面有用户取得团队分佣，计算用户当前团队分佣比例是否比前面用户的高，高则计算出当前用户佣金并减掉前面用户的佣金，低则不分佣
                            }else $userInvite[$item]['commit'] = $total*$value['team']; #前面无用户取得团队分佣，直接计算用户当前团队佣金
                        }
                        #如果前面有用户取得团队分佣，并且用户当前团队分佣比例比前面用户的低则计算管理津贴
                        if(!empty($levelInfo[$levels]['team'])&&$value['team'] <= ($levelInfo[$levels]['team']/100)&&!empty($value['manage'])&&$value['manage']>0)
                            $userInvite[$item]['manage_commit'] = $total*$value['manage'];
                        else
                            $userInvite[$item]['manage_commit'] = 0;
                        $levels = $value['level'];
                    }else{
                        $userInvite[$item]['commit'] = 0;
                        $userInvite[$item]['manage_commit'] = $total*$value['manage'];
                    }
                }else{
                    $levels = $value['level'];
                    $userInvite[$item]['commit'] = $total*($value['team']??0);
                    $userInvite[$item]['manage_commit'] = 0;
                }
                $is_manage_commit = $value['level'];
            }
            $miao = $wallet = [];$i = 0;$time = time();
            $updateInfoSql = 'insert into m3_user_info (uid,consume,team_consume,team_order_num)  values(%s,%s,%s,%s) on  DUPLICATE key update consume=consume+values(consume),team_consume=team_consume+values(team_consume),team_order_num=team_order_num+values(team_order_num)';
            $this::startTrans();
            foreach($userInvite as $k=>$v){
                $commit = ($v['commit']+$v['manage_commit']);
                if($data['type'] == 2){
                    $wallet[$i] = ['uid'=>$v['uid'],'reward'=>$total,'status'=>1,'type'=>5,'extend'=>'user_volume','extend_id'=>$oid,'add_time'=>$time];
                    if($v['uid'] == $data['uid']){
                        $wallet[$i]['describe'] = '个人累计消费';
                        if($commit>0){
                            $i=$i+1;
                            $wallet[$i] = ['uid'=>$v['uid'],'reward'=>$commit,'status'=>1,'type'=>2,'extend'=>'user_volume','extend_id'=>$oid,'add_time'=>$time,'describe'=>'购物券团队结算(喵呗)'];
                        }
                        if(!empty($v['binding_time'])&&$v['binding_time']>0&&$v['binding_time']<=$time){
                            $sql = sprintf($updateInfoSql, $v['uid'], $total, 0, 1);//更新用户绑定后消费数据
                            if(!Db::execute($sql))
                                fileLog(date('Y-m-dHis',time()).'-volume回调-团队结算-更新userInfo失败：'.json_encode(['sql'=>$sql,'uid'=>$v['uid'],'total'=>$total]),'volume_update_userInfo.log');
                        }
                        $userWallet = [
                            'miao'=>$v['miao']+$commit,
                            'miaos'=>$v['miaos']+$commit,
                            'consume'=>$v['consume']+$total,
                            'teams'=>$v['teams'],
                        ];
                    }else{
                        $wallet[$i]['describe'] = '团队累计消费';
                        if($commit>0){
                            $i=$i+1;
                            $wallet[$i] = ['uid'=>$v['uid'],'reward'=>$commit,'status'=>1,'type'=>2,'extend'=>'user_volume','extend_id'=>$oid,'add_time'=>$time,'describe'=>'购物券团队结算(喵呗)'];
                        }
                        $userWallet = [
                            'miao'=>$v['miao']+$commit,
                            'miaos'=>$v['miaos']+$commit,
                            'consume'=>$v['consume'],
                            'teams'=>$v['teams']+$total,
                        ];
                        $sql = sprintf($updateInfoSql, $v['uid'], 0, $total, 1);//更新用户绑定后消费数据
                        if(!Db::execute($sql))
                            fileLog(date('Y-m-dHis',time()).'-volume回调-团队结算-更新userInfo失败：'.json_encode(['sql'=>$sql,'uid'=>$v['uid'],'total'=>$total]),'volume_update_userInfo.log');
                    }
                    $wl = $model->where('uid',$v['uid'])->update($userWallet);
                    #遍历对比等级表判断用户是否满足升级条件,满足则提升用户等级
                    $invites = $userModel->where(['invite_id'=>$v['uid'],'is_delete'=>0])->count();
                    $teams = $userInviteModel->loopInvite($v['uid']);
                    foreach($level as $ki=>$vi){
                        if(($v['consume']+$v['teams']+$total) >= $vi['level_val']){
                            if($vi['direct_push'] <= $invites && $vi['team_num'] <= count($teams))
                                $userInvite[$k]['newLevel'] = $vi['id'];
                        }
                    }
                    fileLog(date('Y-m-dHis',time()).'-volume回调-团队结算-testLevel：'.json_encode(['uid'=>$v['uid'],'invites'=>$invites,'teams'=>count($teams),'userInvite'=>$userInvite,'level'=>$level]),(date('Y-m-d').'_volume_update_level.log'));
                    if($userInvite[$k]['newLevel'] > $v['level']){
                        $userModel->where(['id'=>$v['uid']])->update(['level'=>$userInvite[$k]['newLevel']]);
                        if($userInvite[$k]['newLevel'] > 1) $userModel->where(['id'=>$v['uid'],'is_proceeds'=>0])->update(['is_proceeds'=>1]);
                        fileLog(date('Y-m-dHis',time()).'-volume回调-团队结算-等级提升：'.json_encode(['level'=>($userInvite[$k]['newLevel'] > $v['level']),'order'=>['level'=>$userInvite[$k]['newLevel']],'uid'=>$v['uid'],'invites'=>$invites,'teams'=>count($teams)]),'volume_newLevel.log');
                    }

                    ++$i;
                }
                if($commit > 0){
                    $miao[$i] = ['uid'=>$v['uid'],'oid'=>$oid,'type'=>3,'order_type'=>$data['type'],'reward'=>$commit,'status'=>(($data['type'] == 2) ? 3 : 1),'money'=>$total,'proportion'=>($v['commit']>0 ? $v['team'] : $v['manage']),'add_time'=>$time,'end_time'=>$time];
                    ++$i;
                }
            }
            fileLog(date('Y-m-dHis',time()).'-volume回调-团队结算-更新userInfo：'.json_encode(['miao'=>$miao,'userInvite'=>$userInvite,'wallet'=>$wallet,'level'=>$level]),(date('Y-m-d').'_volume_update_userInfo.log'));

            if(!empty($wallet)){
                if($data['type'] == 2&&!empty($wallet)){
                    $wallet = array_values($wallet);
                    (new WalletOperationLog())->insertAll($wallet);
                }
            }
            if(!empty($miao)){
                $miao = array_values($miao);
                if($this->insertAll($miao)){
                    $this::commit();
                    return true;
                }
                fileLog(date('Y-m-dHis',time()).'-volume回调-团队结算-喵呗新增失败：'.json_encode(['userInvite'=>$userInvite,'order'=>$order,'miao'=>$miao,'wallet'=>$wallet]),(date('Y-m-d').'_volume_miao_error.log'));
                //exception('miao_log 新增失败!');
            }else{
                $this::commit();
                fileLog(date('Y-m-dHis',time()).'-volume回调-没有喵呗记录：'.json_encode(['userInvite'=>$userInvite,'order'=>$order,'miao'=>$miao,'wallet'=>$wallet]),(date('Y-m-d').'_volume_miao_error.log'));
                //exception('没有miao_log!');
            }
            return false;
        }catch (\Exception $e){
            $this::rollback();
            fileLog(date('Y-m-dHis',time()).'-volume回调-团队结算异常：'.json_encode(['data'=>$data,'order'=>$order,'err'=>$e->getMessage()]),(date('Y-m-d').'_volume_miao_error.log'));
            $this->error = $e->getMessage();
            return false;
        }
    }
}
